// ActionScript file




import com.artesophy.library.ImageFilters;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.errors.IllegalOperationError;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.*;
import flash.system.Security;
import flash.system.System;
import flash.utils.ByteArray;

import mx.collections.ArrayCollection;
import mx.controls.*;
import mx.core.INavigatorContent;
import mx.managers.PopUpManager;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.ObjectProxy;
import mx.utils.object_proxy;

import org.osmf.elements.ImageLoader;

import spark.components.Image;
import spark.components.VGroup;
import spark.effects.Fade;
import spark.filters.ColorMatrixFilter;
import spark.primitives.BitmapImage;
import spark.primitives.Rect;

private static const UPLOAD_URL:String = "/photo/api/upload_receive.php";			
private static const IMAGE:String = "이미지";			
private static const MODE_BROWSE:String = "fileModeBrowse";
private static const MODE_UPLOAD:String = "fileModeUpload";

[Bindable]public var fileMode:String;

private var maxFileSize:Number = 4000;			
private var fileReference:FileReference;
private var fileFilter:FileFilter;
private var fileType:String;
private var isReady:Boolean;

[Bindable]public var photoList:ArrayCollection = new ArrayCollection();



/* Set up our application */
private function init():void			
{
	
	
	isReady = true;
	assignFileType();
	
	//Set up the file upload components
	fileMode = "";
	//pb_progress.label = "Select File Type";
	fileReference = new FileReference();
	addListeners();
	
	initAllStatus();
	
	getUserInfoFromWebJS();
}

private function initAllStatus():void{
	initLayouts();
	initListItems();
}

private function initListItems():void{
	if(list_photoList.dataProvider){
		list_photoList.dataProvider.removeAll();
	}
	
	
	for(var i:int=0; i<3; i++){
		addPhotoListLine();
	}
	
}

private function initLayouts():void{
	group_done_btn_set.visible = false;
	group_errMsg.visible = false;
	img_groupThumb.source = "/photo/assets/default_g_thumb.png";
	tarea_titleTweet.text = "";
}

protected var myExternalUserInfo:ExternalUserInfo;
private function getUserInfoFromWebJS():void{
	myExternalUserInfo = new ExternalUserInfo();
}

private function addPhotoListLine():void{
	var obj:ObjectProxy = new ObjectProxy();
	obj.image = "/photo/assets/add_new_photo.png";
	//obj.text = "새 사진";
	obj.text = "";
	obj.isEmpty = true;
	photoList.addItem(obj);
	//list_photoList.add
	list_photoList.dataProvider = photoList;
	
}

private function validateChars(target:String):void{
	
	switch (target){
		case 'title':
			lab_remainChars.text = (110 - int(tarea_titleTweet.text.length)).toString();
			break;
	}
	
}


/* Register all of our event handlers and listeners */		
private function addListeners():void 
{
	fileReference.addEventListener( Event.CANCEL, cancelHandler );
	fileReference.addEventListener( Event.SELECT, selectHandler );
	fileReference.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
	fileReference.addEventListener( ProgressEvent.PROGRESS, progressHandler );
	fileReference.addEventListener( Event.COMPLETE, completeHandler );
}

/* We can assign the correct file filters based on the selected check box */
private function assignFileType():void 
{
	
	isReady = true;
	
	//Set the fileType to image
	fileType = "image";
	
	//Display to user to browse
	//pb_progress.label = "Browse for File";
	
	//Filter the files based on fileType
	fileFilter = new FileFilter( "이미지파일 (*.jpg; *.jpeg; *.gif; *.png;)",
		"*.jpg; *.jpeg; *.gif; *.png" );
	//filterFileType();
	
}			

/* Filter the different filetypes */
/*
private function filterFileType():void 
{
switch ( fileType )
{
case "image": 
fileFilter = new FileFilter( "Images (*.jpg; *.jpeg; *.gif; *.png;)",
"*.jpg; *.jpeg; *.gif; *.png" );
break;

case "document":
fileFilter = new FileFilter( "Documents (*.pdf; *.txt; *.doc; *.rtf;)", 
"*.pdf; *.txt; *.doc; *.rtf;" );
break;

case "compressed":
fileFilter = new FileFilter( "Compressed (*.zip; *.rar; *.7zip;)", 
"*.zip; *.rar; *.7zip;" );
break; 				
}

}
*/

/** validate 이후 업로드 시작. */
private function onClickUpload():void 
{
	if(validBeforeUpload()){
		uploadFile();
	}else{
		lab_errMsg.text = validFailMsg;
		group_errMsg.visible = true;
	}
}

private var validFailMsg:String;
private function validBeforeUpload():Boolean{
	// check is null in title text.
	if( tarea_titleTweet.text == null || tarea_titleTweet.text == ""){
		validFailMsg = "타이틀 메시지를 입력해주세요.";
		return false;
	}
	
	// 사진이 하나라도 있는지 체크.
	var picCount:int = 0;
	for(var i:int=0; i<list_photoList.dataProvider.length; i++){
		if( list_photoList.dataProvider[i].isEmpty == false ){
			picCount++;
		}
	}
	if( picCount == 0 ){
		validFailMsg = "업로드 할 사진이 하나도 없습니다.";
		return false;	
	}
	
	return true;
}

/* Open up the browse for file window */
private function openBrowseWindow():void 
{
	try
	{
		fileReference.browse([fileFilter]);
	}
	catch ( illegalOperation:IllegalOperationError )
	{
		//Alert.show( String(illegalOperation.type), "illegal operation error", 0);
	}
}

/* Our select handler for checking the filesize, etc */
private function selectHandler( event:Event ):void 
{
	//Get the filesize
	var fileSize:Number = Math.round( fileReference.size/1024 );
	
	//Set the filename input to the filename of the file
	//txt_filename.text = fileReference.name;
	
	//Set the filesize text to the size of the file for upload
	//txt_filesize.text = String( fileSize ) + "kb";
	
	//If the current file size is less or equal to our max file size then up
	if ( fileSize <= maxFileSize )
	{
		//Set the fileMode to upload
		fileMode = MODE_UPLOAD;
		
		//Set the label on the progress bar
		//pb_progress.label = "Click Upload";
		
	} else {
		//If the file is to big, alert the user
		//Alert.show( String("File is to large! \n\nPlease select a file smaller than "+ fileSize + "kb" ), "File Size Error", Alert.OK );
	}
}


public var isUploading:Boolean = false;
public var uploadingIdx:int = 0;
/** 
 * 처음 업로드. (photo group 생성 요청)
 * */
public function uploadFile():void 
{
	var request:URLRequest = new URLRequest();
	request.url = UPLOAD_URL;
	
	var params:URLVariables = new URLVariables();
	params.FileType = fileType;
	request.method = URLRequestMethod.POST;
	
	isUploading = true;
	uploadingIdx = 0;
	
	// 업로드 과정 view
	group_errMsg.visible = true;
	lab_errMsg.text = "업로드를 시작합니다.";
	
	//list_photoList.dataGroup.getElementAt(0)["uploadPic"](request, prepareParams());
	requestMakeGroup(request, prepareParams("PHOTO_GROUP"));
	
	//request.data = params;
	
	//fileReference.upload( request, "photo_group" );
}



public function requestMakeGroup(request:URLRequest, objParams:Object):void{
	
	var httpserv_params:Object = new Object();
	httpserv_params["idx"] = objParams['idx'];
	httpserv_params["gPhotoText"] = objParams["gPhotoText"];
	httpserv_params["tweetByPhoto"] = objParams["tweetByPhoto"];
	httpserv_params['groupThumbIdx'] = objParams["groupThumbIdx"];
	
	httpserv_requestMakePhotoGroup.url = request.url;
	lab_ver.text += ("destination url : " + httpserv_requestMakePhotoGroup.url);
	
	httpserv_requestMakePhotoGroup.send(httpserv_params);
	
	lab_errMsg.text = "타이틀에시지 등록 중...";
}

private var uploadingGroupIdx:int = 0;
private function requestMakePhotoGroup_result(event:ResultEvent):void{
	lab_ver.text += ("received data : " + event.result.toString());	
	var CODE:String = event.result.toString().substr(event.result.toString().search("CODE:")+5,3);
	var DATA:String = event.result.toString().substr(event.result.toString().search("DATA:")+5);
	lab_ver.text += ("DATA : "+DATA);
	if(CODE == "101"){// photo group uploaded.
		uploadingGroupIdx = int(DATA);
		saveGroupDone();
	}
}

private function uploadCompleteHandler(event:Event):void{
	
}

private function receivedHandler(event:DataEvent):void{
	
}

private function uploadIoErrorHandler(event:IOErrorEvent):void{
	lab_ver.text += ("occur io error : " + event.text);
}

public function saveGroupDone():void{
	lab_ver.text += ("Saved Group Done.");
	lab_errMsg.text = "타이틀 등록 완료";
	
	photoUpload(uploadingIdx);
}

public function photoUpload(idx:int):void{
	lab_ver.text += ("photoUpload started = " + idx);
	var request:URLRequest = new URLRequest();
	request.url = UPLOAD_URL;
	request.method = URLRequestMethod.POST;
	
	/*
	var params:URLVariables = new URLVariables();
	params.FileType = fileType;
	*/
	
	lab_errMsg.text = "사진 업로드 중 : (" + (idx + 1) + "/" + list_photoList.dataProvider.length + ")";
	list_photoList.dataGroup.getElementAt(idx)['uploadPhoto'](request, prepareParams("PHOTO"));
	//list_photoList.dataProvider.getItemAt(idx).uploadPhoto(request, prepareParams("PHOTO"));
}

private function prepareParams(mode:String):Object{
	var objParams:Object = new Object;
	//objParams['idx'] = "oadgkkrz8Dcdmi%252F66iQs8tgGD14IrA7lgBbd54jB%252FNs%253D";
	objParams['idx'] = myExternalUserInfo.cookie_u;
	//lab_ver.text += " " + objParams['idx'];
	objParams['gPhotoText'] = tarea_titleTweet.text;
	objParams['tweetByPhoto'] = (cbox_tweetByPhoto.selected) ? "1" : "0";
	objParams['groupThumbIdx'] = groupThumbIdx;
	
	if(mode == "PHOTO"){
		objParams['gPhotoIdx'] = uploadingGroupIdx;
		objParams['idxInGroup'] = uploadingIdx;
	}
	
	// 이후 externalInterface 를 이용하여 parameters 를 가져오는 것으로 변경 필요.
	
	return objParams;
}

/** 
 * uploadFile 에서 groupid 값 받고, 계속해서 업로드 할 파일이 남아있으면 이 함수에서 이후 사진들을 업로드. 
 * 업로드 완료 후에, 업로드 완료 했다는 msg 출력.
 * */
public function uploadPhotoDone():void{
	lab_ver.text += ("uploadPhotoDone");
	uploadingIdx += 1;
	lab_errMsg.text = "사진 업로드 완료 : ("+uploadingIdx.toString()+"/"+list_photoList.dataProvider.length+")";
	if(uploadingIdx > list_photoList.dataProvider.length - 1){
		allUploadDone();
	}else{
		photoUpload(uploadingIdx);
	}
}

private function allUploadDone():void{
	lab_ver.text += ("allUploadDone");
	lab_errMsg.text = "업로드가 모두 완료되었습니다.";
	lab_errMsg.setStyle("color", "#989ef1");
	// reset ui, empty items, reset variable.
	isUploading = false;
	uploadingIdx = 0;
	
	group_done_btn_set.visible = true;
}


/* Handles our progress bar */	
private function progressHandler( event:ProgressEvent ):void 
{
	//Set the progress to our bytesLoaded, and bytesTotal
	//pb_progress.setProgress( event.bytesLoaded, event.bytesTotal );
	
	//Set the label to uploading and do alittle math of displaying the current progress
	//pb_progress.label = "Uploading " + Math.round( event.bytesLoaded / 1024 ) + " kb of " +
		Math.round( event.bytesTotal / 1024 ) + " kb ";
	
}	

/* Just incase our user wants to cancel the upload */
private function onClickClose():void 
{				
		
	if(this.currentState == "main"){
		//Cancel the fileref
		fileReference.cancel();
		
		//Reset the uploader
		resetUploader();
		ExternalInterface.call("hideUploader");
	}else if(this.currentState == "edit"){
		closeEditor();
	}
}

private function closeEditor():void{
	this.currentState = "main";
}

/* We can handle the canceled download */
private function cancelHandler( event:Event ):void 
{
	//Alert.show( "File Upload Cancelled" );
}	

/* IO Error handler */			
private function ioErrorHandler( event:IOErrorEvent ):void 
{
	//Alert of the error
	//Alert.show( String( event.type ), "IOError", 0 );
	
	//Reset the uploader
	resetUploader();
}

/* Complete handler */
private function completeHandler( event:Event ):void 
{			
	var file:FileReference = FileReference( event.target );
	var fileURL:String = file.name;
	
	//Show the user the uploaded file
	//Alert.show( String( fileURL ), "File Uploaded", Alert.OK );
	
	//Reset the uploader
	resetUploader();
}

/* Reset the filemode, inputs, progress bar and selected check boxes */
private function resetUploader():void 
{
	fileMode = "";
	
	//isReady = false;
	
	//txt_filename.text = "";
	//txt_filesize.text = "";
	
	//pb_progress.label = " Select File Type";
	//pb_progress.maximum = 0;
	//pb_progress.minimum = 0;
	
}

private function onClickMsg():void{
	group_errMsg.visible=false;
	lab_errMsg.setStyle("color", "#fcaaaa");
}

private function countPhoto():int{
	var picCount:int = 0;
	for(var i:int=0; i<list_photoList.dataProvider.length; i++){
		if( list_photoList.dataProvider[i].isEmpty == false ){
			picCount++;
		}
	}
	
	return picCount;
}

private function findFirstIdx():int{
	var firstIdx:int = 0;
	for(var i:int=0; i<list_photoList.dataProvider.length; i++){
		if( list_photoList.dataProvider[i].isEmpty == false ){
			return i;
		}
	}
	
	return firstIdx;
}
/*
public function selectGroupThumb(selectedIdx:int):void{
	isSelectedGroupThumb = true;
	
	trace("chkchk : " + selectedIdx.toString());
	img_groupThumb.source = list_photoList.dataProvider[selectedIdx].image;
}
*/

// 수동으로 그룹 썸네일을 지정하였는지. 수동으로 지정한 적이 있으면 자동으로 firstIdx의 thumbnail을 groupThumbnail 로 할당하지 않는다.
public var isSelectedGroupThumb:Boolean = false;

public function addGroupThumb():void{
	img_groupThumb.source = list_photoList.dataProvider.getItemAt(findFirstIdx()).image;
	if(list_photoList.dataProvider.length < 10){
		addPhotoListLine();
	}
}


private function onClickGroupThumb():void{
	
}

public var groupThumbIdx:int = 0;
public function saveGroupThumbIdx():void{
	groupThumbIdx = list_photoList.selectedIndex;
}

public function openEditor():void{
	this.currentState = "edit";
	img_editingPhoto.imageDisplay.filters = [];
	img_editingPhoto.source = list_photoList.dataProvider[list_photoList.selectedIndex].image;
}

private var filterer:ImageFilters = new ImageFilters();
private function preApplyFilter(mode:String):void{	
	filterer.preApplyFilter(img_editingPhoto.imageDisplay, mode);
}

private function applyFilter():void{
	var filteredImageData:BitmapData = filterer.getFilteredImage();
	this.currentState = "main";
	list_photoList.dataProvider[list_photoList.selectedIndex].image = filteredImageData;
	addGroupThumb();
}

/*
private function onClickUploadResume():void{
//initAllStatus();
}
*/

private function onClickViewPost():void{
	navigateToURL(new URLRequest("http://twitaddons.com/photo/view.php?isgroup=t&id=" + uploadingGroupIdx.toString()), "_new");
}


private var eff_fade:Fade = new Fade();
private function onOverFilterPalette():void{
	eff_fade.target = group_filter_palette;
	eff_fade.alphaFrom = 0;
	eff_fade.alphaTo = 1;
	eff_fade.duration = 500;
	eff_fade.play();
}

private function onOutFilterPalette():void{
	eff_fade.target = group_filter_palette;
	eff_fade.alphaFrom = 1;
	eff_fade.alphaTo = 0;
	eff_fade.duration = 500;
	eff_fade.play();
}

private function onChangeFilterAlpha(alpha:Number):void{
	filterer.changeAlpha(alpha);
}

private function onClickBackLayer():void{
	
}